<?php

namespace app\shop\controller;

// 框架基础控制类
use think\Controller;

class Base extends Controller
{
    //构造函数
    public function __construct()
    {
        //手动把父类的方法获取过来
        parent::__construct();

        // 全局用户模型
        $this->BusinessModel = model('Business.Business');

    }

    // 注册
    public function register()
    {

        if ($this->request->isPost()) {

            $mobile = $this->request->param('mobile', '', 'trim');

            $password = $this->request->param('password', '', 'trim');

            // 判断当前手机号码是否已注册
            $userinfo = $this->BusinessModel->where('mobile', $mobile)->find();

            if ($userinfo) {
                $this->error('当前手机号码已注册，请重新输入');
            }

            // 密码盐
            $salt = randstr();

            // 密码加密
            $password = md5($password . $salt);

            $data = [
                'mobile' => $mobile,
                'password' => $password,
                'salt' => $salt
            ];

            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if ($result) {
                $this->success('注册成功');
            } else {
                $this->error($this->BusinessModel->getError());
            }
        }
    }

    // 登陆
    public function login()
    {
        if ($this->request->isPost()) {

            $mobile = $this->request->param('mobile', '', 'trim');

            $password = $this->request->param('password', '', 'trim');

            // 查找当前手机号码
            $userinfo = $this->BusinessModel->where('mobile', $mobile)->find();

            if (!$userinfo) {
                $this->error('当前用户不存在');
            }

            $password = md5($password . $userinfo['salt']);

            if ($password != $userinfo['password']) {
                $this->error('密码错误，请重新输入');
            }

            $data = [
                'id' => $userinfo['id'],
                'mobile' => $userinfo['mobile'],
                'nickname' => $userinfo['nickname'],
                'avatar' => $userinfo['avatar_cdn'],
                'gender' => $userinfo['gender'],
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'district' => $userinfo['district'],
                'point' => $userinfo['point'],
                'region' => $userinfo['region_text'],
                'email' => $userinfo['email'],
                'auth' => $userinfo['auth']
            ];

            $this->success('登陆成功', '',  $data);
        }
    }

    // 校验
    public function check()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '0', 'trim');

            $userinfo = $this->BusinessModel->find($id);

            if (!$userinfo) {
                $this->error('当前用户不存在，请去注册');
            }

            // 组装数据
            $data = [
                'id' => $userinfo['id'],
                'mobile' => $userinfo['mobile'],
                'nickname' => $userinfo['nickname'],
                'avatar' => $userinfo['avatar_cdn'],
                'gender' => $userinfo['gender'],
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'district' => $userinfo['district'],
                'point' => $userinfo['point'],
                'region' => $userinfo['region_text'],
                'email' => $userinfo['email'],
                'auth' => $userinfo['auth']
            ];

            $this->success('', '',  $data);
        }
    }

    // 修改资料
    public function profile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $password = $this->request->param('password', '', 'trim');

            $userinfo = $this->BusinessModel->find($params['id']);

            if (!$userinfo) {
                $this->error('当前用用户不存在');
            }

            $data = [
                'id' => $params['id'],
                'mobile' => $params['mobile'],
                'nickname' => $params['nickname'],
                'gender' => $params['gender'],
                'email' => $params['email'],
            ];
           
            // 修改省市区  null空值
            if (isset($params['district']) && !empty($params['district'])) {

                $parentpath = $params['province'] . ',' . $params['city'] . ',' . $params['district'];

                $path = $this->RegionModel->where('parentpath', $parentpath)->find();

                if (!$path) {
                    $this->error('当前选择的地区不存在');
                }

                $data['province'] = $params['province'];
                $data['city'] = $params['city'];
                $data['district'] = $params['district'];
            }

            // 校验密码
            if ($password) {
                $password = md5($password . $userinfo['salt']);

                if ($password == $userinfo['password']) {
                    $this->error('与旧密码一致，请请重新输入');
                }

                $data['password'] = $password;
            }
      
            // 图片上传
            if(isset($_FILES['avatar']) && $_FILES['avatar']["size"] > 0)
            {
                $res = upload('avatar');
                if($res['code'] == 1)
                {
                    $data['avatar'] = $res['url'];
                } else {
                    $this->error('头像上传失败');
                }
            }

            $result = $this->BusinessModel->isUpdate()->save($data);

            if($result)
            {
                // 册除旧的图片
                if(isset($_FILES['avatar']) && $_FILES['avatar']["size"] > 0)
                {
                    $avatar = substr($userinfo['avatar'],1); 
                    @is_file($avatar) && @unlink($avatar);
                }
                $this->success('修改资料成功');
            } else {
                // 册除新的图片
                if(isset($_FILES['avatar']) && $_FILES['avatar']["size"] > 0)
                {
                    $avatar = substr($data['avatar'],1); 
                    @is_file($avatar) && @unlink($avatar);
                }
                $this->error($this->BusinessModel->getError());
            }
        }
    }

    // 发送邮件
    public function send()
    {
        if ($this->request->isPost()) 
        {
            $id = $this->request->param('id', '0', 'trim');
            $email = $this->request->param('email', '', 'trim');

            $userinfo = $this->BusinessModel->find($id);

            if(!$userinfo){
                $this->error('当前用户不存在');
            }

            if(empty($email)){
                $this->error('邮箱不能为空');
            }

            // 生成验证码
            $code = randstr(4);

            $data = [
                'event' => '邮箱认证',
                'email' => $email,
                'code' => $code
            ];

            $this->EmsModel->startTrans();

            $result = $this->EmsModel->validate('common/Business/Ems')->save($data);

            if($result ===  false){
                $this->EmsModel->rollback();
                $this->error('邮件发送失败');
            }
            // 发送邮件
            $emailstatus = send_email($email, $code);

            if($result && $emailstatus == true){

                $this->EmsModel->commit();
                $this->success('邮件发送成功');
            }  else {

                $this->EmsModel->rollback();
                $this->error($this->EmsModel->errors());
            }
        }
    }

    // 验证邮件
    public function checkmail()
    {
        if ($this->request->isPost()) 
        {
            $id = $this->request->param('id', '0', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            $userinfo = $this->BusinessModel->find($id);

            if(!$userinfo){
                $this->error('当前用户不存在');
            }

            if(empty($email)){
                $this->error('邮箱不能为空');
            }

            if(empty($code)){
                $this->error('验证码不能为空');
            }

            if($userinfo['auth'] == 1){
                $this->success('当前邮箱已认证，无需再认证');
            }

            $emsinfo = $this->EmsModel->where(['email' => $email, 'code' => $code])->find();

            if(!$emsinfo){
                $this->error('验证码错误，请重新新输入');
            }
       
            // 验证码的时间 验证码失效时间   3600*24: 1天
            $checktime  = strtotime($emsinfo['createtime']) + 120;
            
            if($checktime < time()){
                $this->EmsModel->destroy($emsinfo['id']);
                $this->error('验证码过期');
            }
            
            //更新验证状态
            // 1.更新用户表 2.验证码的删除
            $this->BusinessModel->startTrans();
            $this->EmsModel->startTrans();

            // 1.更新用户表 
            $data = [
                'id'=>  $id,
                'auth' => 1
            ];

            $businesStatus = $this->BusinessModel->isUpdate()->save($data);
            
            if($businesStatus === false) {
                $this->BusinessModel->rollback();
                $this->error($this->BusinessModel->getError());
            }

            $emsStatus = $this->EmsModel->destroy($emsinfo['id']);

            if($emsStatus === false) {
                $this->EmsModel->rollback();
                $this->BusinessModel->rollback();
                $this->error($this->EmsModel->getError());
            }

            if($emsStatus === false || $businesStatus === false){
                $this->EmsModel->rollback();
                $this->BusinessModel->rollback();
                $this->error('邮箱认证失败');
            } else {
                $this->EmsModel->commit();
                $this->BusinessModel->commit();
                $this->success('邮箱认证成功');
            }

        }
    }
}
